package com.atguigu.gmall.common.util;

import com.atguigu.gmall.model.to.CategoryTo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author 卡尼奶
 * @Date 2022/5/22 21:13
 * @Version 1.0
 */
@Slf4j
public class JSONStr {
    public static final ObjectMapper objectMapper = new ObjectMapper();

    public static String toJsonStr(Object obj){
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.error("JSON转换异常：{}",obj);
        }
        return null;
    }

    public static <T> T strToObj(String strJson, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(strJson, typeReference);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T nullObj(TypeReference<T> typeReference) {
        String json = "[]";
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
